<template>
  <!-- v-loading="true" -->
  <div>
    <pageSearch :searchFormConfig="searchFormConfig" @searchSubmit="searchSubmit" />
    <pageTable :tableData="tableData" :tableInit="params.tableInit" @sizeChange="sizeChange"
      @currentChange="currentChange" @exportFn="exportExcel" v-loading="loading" @pageAdd="openDialogFn('新增')">

      <template #operation="{ row }">
        <el-button type="primary" link @click="openDialogFn('编辑', row)">编辑</el-button>
        <el-popconfirm title="确认要删除吗?" @confirm="delData(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>



    </pageTable>

    <Dialog width="1200px" top="5vh" ref="DialogRef" :title="typeText" @submit="submitForm(ruleFormRef)"
      @onclose="resetForm(ruleFormRef)">
      <el-form ref="ruleFormRef" v-loading="DialoLoading" :model="ruleForm" status-icon :rules="rules"
        label-width="120px" class="demo-ruleForm">

        <el-row :gutter="20">

          <el-col :span="24">
            <div>评估板基本信息</div>
            <el-divider />
          </el-col>

          <el-col :span="12">
            <el-form-item label="评估板名称" prop="name">
              <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="评估板简介" prop="scopes">
              <el-input v-model="ruleForm.scopes" autocomplete="off" placeholder="请输入产品简介"
                :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
            </el-form-item>
          </el-col>



          <el-col :span="24">
            <el-form-item label="评估板图片" prop="images" v-if='!DialoLoading'>
              <LTUpload tip="建议图片尺寸1800*1200" v-model="ruleForm.images" :limit="5"></LTUpload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="数据表" v-if='!DialoLoading'>
              <uploadFiles v-model="ruleForm.linklist" @onPreviewFn="onPreviewFN" :limit="10"></uploadFiles>
            </el-form-item>
          </el-col>








          <el-col :span="24">
            <el-form-item label="评估板描述">
              <el-row class="w-full">
                <el-col :span="24" class="mb-[15px]" v-for="(item, index) in ruleForm.descriplist" :key="index">
                  <el-input v-model="item.description" autocomplete="off" placeholder="请输入产品说明" />
                </el-col>
                <el-col :span="24" class="">
                  <el-button @click="addruleFormcpsm">添加新描述</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col>


          <el-col :span="24" class="mt-8">
            <div>产品设计和开发</div>
            <el-divider />
          </el-col>

          <el-col :span="24">
            <el-form-item label="评估板">
              <el-select collapse-tags collapse-tags-tooltip style="width: 20%" multiple v-model="ruleForm.sjzylist"
                placeholder="请选择">
                <el-option v-for="option in pingGuList" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="支持软件">
              <el-select style="width: 20%" multiple v-model="ruleForm.zcrjlist" placeholder="请选择">
                <el-option v-for="option in selfzwjpageList" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>






          <el-col :span="24" class="mt-8">
            <div>技术文档</div>
            <el-divider />
          </el-col>

          <el-col :span="24">
            <el-form-item label="" label-width="0">
              <el-row class="w-full pb-4" v-if="ruleForm.list.length > 0">

                <el-col :span="4" class="text-center">
                  文档/文章
                </el-col>

                <el-col :span="3" class="text-center">
                  文档类型
                </el-col>
                <el-col :span="6" class="text-center">
                  文档
                </el-col>
                <!-- <el-col :span="3" class="text-center">
                  文档格式
                </el-col> -->
                <el-col :span="4" class="text-center">
                  文档权限
                </el-col>
                <el-col :span="4" class="text-center">
                  文档时间
                </el-col>
                <el-col :span="3" class="text-center">
                  操作
                </el-col>
              </el-row>
              <el-row class="w-full " v-if='!DialoLoading'>
                <el-col :span="24">
                  <template v-for="(v, index) in ruleForm.list" :key="v.webId">
                    <div class="mb-4">
                      <technicalFile @delItemFn="delItemFN" :itemIndex="index" :searchList="filesStatus"
                        v-model="ruleForm.list[index]"></technicalFile>

                    </div>
                  </template>
                </el-col>
              </el-row>


              <el-row class="w-full">
                <el-col :span="24">
                  <el-button @click="addtechnicalFile">添加文档</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col>













        </el-row>
      </el-form>



    </Dialog>

    <el-dialog v-model="dialogTableVisible" title="预览">
      <pdfPage v-if="pdfUrl" :source='pdfUrl'></pdfPage>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pageTable from "@/components/base-ui/page-table";
import pageSearch from "@/components/base-ui/page-search";
import Dialog from "@/components/base-ui/dialog";
import { reactive, ref, computed } from 'vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { clone } from "@pureadmin/utils";
import { randomString } from '@/utils/xwCommon'
import { tableInit } from "./config/listTable.config";
import { searchFormConfig } from "./config/listSearch.config";
import { usepageTable } from '@/components/base-ui/page-table/usePageTable'
import technicalFile from './components/technicalFile.vue'
import { getselpage } from '@/api/classification'
import uploadFiles from '@/components/base-ui/uploadFiles'
import LTUpload from '@/components/base-ui/upload'
import { getproductdictionaryselpage, productdictionaryselzdandzdinfo } from '@/api/productdictionary'
import { getselpackagepage, getselfzwjpage, getPingGuBan } from '@/api/designsupport'
import { getPicImg, geturlneeddl } from '@/api/upload'
import { message } from "@/utils/message";
import pdfPage from "@/components/base-ui/pdf";
import { getevaluationeditionlist, getevaluationboardinfo, evaluationboardgrclass, evaluationboarddelinfo, evaluationboardinserpro } from '@/api/evaluationeditionlist'
import { sjcyzcrjselfzwjpage } from '@/api/supportsoftware'
import dayjs from "dayjs";


const {
  exportExcel,
  tableData,
  getData,
  params,
  loading,
  sizeChange,
  serachVal,
  currentChange,
  delData,
  DialogRef,
  searchSubmit,
  openDialog,
  productStatus,
  filesStatus
} = usepageTable({
  tableInit,
  getRes: getevaluationeditionlist,
  delRes: evaluationboarddelinfo,
})

getData()


// 搜索
const serachForm = reactive({
  name: '',
  productclassone: '',  //一级产品类名称
  productclassoneid: '',  //一级产品类id（大类）
  productclasstwo: '',  //二级产品类名称（下级）
  productclasstwoid: '',  //二级产品类id（下级）
})






// 分页查询仿真文件信息
const selfzwjpageList = ref([])
const getgetselfzwjpageList = () => {
  sjcyzcrjselfzwjpage({
    index: 1,
    size: 10000
  }).then(res => {
    selfzwjpageList.value = res.result
  })
}
getgetselfzwjpageList()

// 查询评估板列表
const pingGuList = ref([])
const getpingGuList = () => {
  getPingGuBan({
    index: 1,
    size: 10000
  }).then(res => {
    pingGuList.value = res.result
  })
}
getpingGuList()


const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({

  name: '',
  scopes: '',
  images: [],
  list: [],
  descriplist: [],
  sjzylist: [],
  zcrjlist: [],
  linklist: []
})



const productclasstwoFormList = computed(v => {
  let item = searchList.value.find(v => ruleForm.productclassoneid == v.id)
  if (item) {
    return item?.list
  } else {
    return []
  }
})


const rules = reactive<FormRules<typeof ruleForm>>({
  name: [
    { required: true, message: '请填写评估板名称', trigger: 'blur' },
  ],
  scopes: [
    { required: true, message: '请填写评估板简介', trigger: 'blur' },
  ],
  images: [
    { required: true, message: '请上传评估板图片，最多5张', trigger: 'blur' },
  ],

})


const addruleFormcpsm = () => ruleForm.descriplist.push({ description: '' })


const addtechnicalFile = () => ruleForm.list.push({ gs: '', level: 0, linkid: '', lx: '', name: '', createTime: dayjs().format("YYYY-MM-DD"), webId: randomString(10), infotype: 0, zdywzid: '' })





const typeText = ref('')
const handleID = ref(null)
const DialoLoading = ref(false)
const openDialogFn = (text, row) => {
  getpingGuList()

  DialoLoading.value = true
  typeText.value = text
  if (row) {
    handleID.value = row.id
    getevaluationboardinfo(row.id).then(res => {
      console.log(res, 'res')

      const result = clone(res.result, true);
      Object.keys(ruleForm).forEach((key) => ruleForm[key] = result[key])

      console.log(ruleForm, 'ruleForm')
      ruleForm.linklist.forEach(v => {
        v.url = geturlneeddl(v.linkid)
      })


      ruleForm.images.forEach(v => {
        v.imgId = v.url
        v.url = getPicImg(v.url)
      })


      if (!ruleForm.list) {
        ruleForm.list = []
      }

      if (ruleForm.list.length > 0) {
        ruleForm.list.forEach(v => {
          v.webId = randomString(10)
        })
      }


      if (result.descriplist != null && result?.descriplist?.length > 0) {
        ruleForm.descriplist = result.descriplist.map(v => {
          return {
            description: v
          }
        })
      } else {
        ruleForm.descriplist = []
      }


      ruleForm.sjzylist = result.xjlist

    }).finally(() => {
      DialoLoading.value = false
    })
  } else {
    DialoLoading.value = false
  }
  openDialog()
}


const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      setProduct()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const setProduct = () => {

  const temporaryList = clone(ruleForm, true);

  // 处理数据表数据
  if (temporaryList.linklist.length > 0) {

    let a = temporaryList.linklist.map(v => {
      return {
        level: 0,
        linkid: v?.response?.data?.result[0]?.uuid ?? v.linkid,
        name: v.name
      }
    })
    temporaryList.linklist = a
  }
  // 处理图片
  if (temporaryList.images.length > 0) {
    let b = temporaryList.images.map(v => {
      return {
        name: v.name,
        url: v?.response?.data?.result[0]?.uuid ?? v.imgId,
      }
    })
    temporaryList.images = b
  }


  // 产品说明列表
  if (temporaryList.descriplist.length > 0) {
    let c = temporaryList.descriplist.filter(v => v.description)
    temporaryList.descriplist = c
  }



  // 处理技术支持
  // if (temporaryList.list.length > 0) {
  //   let f = temporaryList.list.filter(v => v.linkid)
  //   temporaryList.list = f
  // }
  // 处理技术支持
  if (temporaryList.list.length > 0) {
    let f = temporaryList.list.filter(v => {
      if (v.infotype == 0) {
        if (v.linkid) {
          return v
        }
      }
      if (v.infotype == 1) {
        if (v.zdywzid) {
          return v
        }
      }
    })
    temporaryList.list = f
  }


  temporaryList.id = handleID.value
  let fn = typeText.value === '新增' ? evaluationboardinserpro : evaluationboardgrclass
  fn(temporaryList).then(res => {
    DialogRef.value.close()
    message("添加成功", {
      type: "success"
    });
    getData()
  })

}


const delItemFN = (index) => ruleForm.list.splice(index, 1)








const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()

  handleID.value = null
  ruleForm.name = ''
  ruleForm.scopes = ''
  ruleForm.images = []
  ruleForm.list = []
  ruleForm.descriplist = []
  ruleForm.sjzylist = []
  ruleForm.zcrjlist = []
  ruleForm.linklist = []

}

const dialogTableVisible = ref(false)
const pdfUrl = ref('')
const onPreviewFN = (e) => {
  pdfUrl.value = e
  dialogTableVisible.value = true
}

</script>

<style scoped>
:deep(.el-form-item__label) {
  font-weight: 600;
}
</style>
